from pywebio.input import input, NUMBER
from pywebio.output import put_text
from pywebio import start_server
from random import randint
from socket import *


def draw(tot):
    while True:
        d = input('你要取的石子数量是(1/2/3)：', type=NUMBER)
        if 0 < d < 4:
            return tot-d
        if d > tot:
            put_text('没有这么多石子噢！')
        else:
            put_text('每人每次只能取1枚，2枚或3枚石子！')


serverName = "localhost"
serverPort = 12000


def main():
    put_text('新年快乐！一起来玩石子游戏吧\n你和系统将会轮流取石子，每人每次只能取1枚，2枚或3枚石子\n先取完所有石子的人获胜')

    n = randint(20, 40)
    while n > 0:
        put_text('现在有{}枚石子，轮到你取啦！'.format(n))
        n = draw(n)
        if n == 0:
            put_text('恭喜你，你赢啦！')
            break

        clientSocket = socket(AF_INET, SOCK_STREAM)
        clientSocket.connect((serverName, serverPort))
        clientSocket.send(str(n).encode())
        revSentence = clientSocket.recv(1024).decode()
        d = int(revSentence)
        n -= d
        if n != 0:
            put_text('系统取了{}枚石子，还剩{}枚石子'.format(d, n))
        else:
            put_text('系统取了{}枚石子，你输啦'.format(d))
            break

start_server(main, port=8082, debug=False)